using Vin.Tool.Core.AssertCategory;

namespace Vin.Tool.Core.IEnumerableCategory;

public static partial class Extension
{
    public static string ToQueryString<TKey, TValue>(this IDictionary<TKey, TValue>? dictionary,
        List<string> appendList) where TKey : notnull
    {
        if (dictionary == null || dictionary.Count == 0)
        {
            return string.Empty;
        }

        var strArray = dictionary
            .Where(kvp => kvp.Value != null) // 过滤掉值为null的键值对
            .Select(kvp =>
                $"{Uri.EscapeDataString(kvp.Key!.ToString()!)}={Uri.EscapeDataString(kvp.Value?.ToString() ?? string.Empty)}")
            .ToList();

        if (appendList.Count == 0)
        {
            strArray.AddRange(appendList);
        }

        return string.Join("&", strArray);
    }

    public static string ToQueryString<TKey, TValue>(this IDictionary<TKey, TValue>? dictionary,
        Dictionary<string, object>? appendDict = null) where TKey : notnull
    {
        if (appendDict != null && appendDict.Count > 0)
            return dictionary.ToQueryString(appendDict.Select(kvp =>
                    $"{Uri.EscapeDataString(kvp.Key)}={Uri.EscapeDataString(kvp.Value?.ToString() ?? string.Empty)}")
                .ToList());

        return dictionary.ToQueryString();
    }

    public static string ToQueryString<TKey, TValue>(this Dictionary<TKey, TValue> dict, string appendStr)
        where TKey : notnull =>
        dict.ToQueryString(new List<string> { appendStr });
}